<template>
  <el-card>
    <!-- 搜索框 -->
    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <el-input placeholder="请输入题目/答案/解析" clearable v-model="queryForm.query"></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="initGetQuestionlist">搜索</el-button>
    </el-row>
    <!-- 筛选 -->
    <el-row :gutter="20" class="header">
      <el-select v-model="queryForm.subjectValue" class="m-2" placeholder="请选择科目">
        <el-option
          v-for="item in queryForm.subject"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="queryForm.typeValue" class="m-2" placeholder="请选择类型">
        <el-option
          v-for="item in queryForm.type"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" :icon="Search" @click="screen">筛选</el-button>
    </el-row>
    <!-- 表单 -->
    <el-table :data="tableData" stripe style="width: 100%" border>
      <el-table-column prop="id" label="编号" width="60px"/>
      <el-table-column prop="title" label="题目" show-overflow-tooltip />
      <el-table-column prop="subject" label="科目" width="90px"/>
      <el-table-column label="类型" width="90px">
        <template #default="scope">
          {{ changeType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="选项" show-overflow-tooltip >
        <template #default="scope">
          <span v-for="item in scope.row.options" :key="item">{{ item.code }}.{{ item.option }};</span>
        </template>
      </el-table-column>
      <el-table-column prop="answer" label="答案" show-overflow-tooltip />
      <el-table-column prop="analysis" label="解析" show-overflow-tooltip />
      <el-table-column label="操作" fixed="right" width="220">
        <template #default="scope">
          <el-button type="primary" size="small" @click="addquestion(scope.row)">加入题库</el-button>
          <el-button size="small" @click="opendialog(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteQuestion(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :page-size="queryForm.pagesize"
      :pager-count="5"
      layout="prev, pager, next"
      :total="queryForm.totle"
      :hide-on-single-page="queryForm.pagesize>=queryForm.totle"
      @current-change="handleCurrentChange"
      :current-page="queryForm.pagename"
    />
  </el-card>
  <!-- 用户信息对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="编辑题目"
    width="50%"
    :show-close="false"
    @close="closedialo"
  >
      <el-form :model="question" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="问题" prop="title">
          <el-input v-model="question.title" maxlength="50" placeholder="请输入题目" show-word-limit type="textarea"/>
        </el-form-item>
        <el-form-item label="是否新添科目" >
          <el-switch v-model="question.isaddsubject" />
        </el-form-item>
        <el-form-item label="科目" v-if="!question.isaddsubject" prop="subject">
          <el-select v-model="question.subject" class="m-2" placeholder="Select">
            <el-option
              v-for="item in subjectlist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="新科目" v-if="question.isaddsubject" prop="newsubject">
          <el-input v-model="question.newsubject" placeholder="请输入新科目英文"/>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="question.type" class="m-2" placeholder="Select" @change="changeSelectType">
            <el-option
              v-for="item in [
                { label: '多选题', value: 'duo' },
                { label: '单选题', value: 'dan' },
                { label: '填空题', value: 'tian' },
                { label: '判断题', value: 'pan' }
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选项" v-if="question.type != 'tian' && question.type != 'pan'" prop="option">
          <el-input v-for="(item, index) in question.options" :key="item" v-model="item.option" placeholder="Please input"  style="margin: 5px 0;">
            <template #prepend>
              <div style="cursor:pointer;" :class="{answer: question.answer.indexOf(String.fromCharCode(65+index)) !== -1}" @click="setanswer(index)">{{ String.fromCharCode(65+index) }}</div>
            </template>
            <template #append>
              <el-button :icon="RemoveFilled" @click="deloption(index)"/>
            </template>
          </el-input>
          <el-button type="primary" style="margin-top: 5px" @click="addoption">添加选项</el-button>
        </el-form-item>
        <el-form-item label="选项" v-if="question.type != 'tian' && question.type == 'pan'" >
          <el-input v-for="(item, index) in ['对的', '错的']" :key="item" :value="item" disabled style="margin: 5px 0;">
            <template #prepend>
              <div style="cursor:pointer;" :class="{answer: question.answer.indexOf(String.fromCharCode(65+index)) !== -1}" @click="setanswer(index)">{{ String.fromCharCode(65+index) }}</div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="question.answer" :disabled="question.type !== 'tian'"/>
        </el-form-item>
        <el-form-item label="解析" prop="analysis">
          <el-input v-model="question.analysis" maxlength="50" placeholder="请输入解析" show-word-limit type="textarea"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="summit(true)">加入题库</el-button>
          <el-button @click="summit(false)">修改内容</el-button>
          <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
  </el-dialog>
</template>

<script setup>
  import { Search, RemoveFilled } from '@element-plus/icons-vue'
  import { ref } from 'vue'
  import { getaddquestionlist, getsubjectlist, setaddquestion, deladdquestion } from '@/api/question'
  import { ElMessage, ElMessageBox } from 'element-plus'

  const queryForm = ref({
    query: '',
    subject: [],
    subjectValue: '',
    type: [
      { label: '多选题', value: 'duo' },
      { label: '单选题', value: 'dan' },
      { label: '填空题', value: 'tian' },
      { label: '判断题', value: 'pan' },
      { label: '请选择类型', value: '' }
    ],
    typeValue: '',
    pagename: 1,
    pagesize: 7,
    totle: 0
  })
  const tableData = ref([])
  const questionlist = ref([])
  const resultlist = ref([])

  // 查询问题列表
  const initGetQuestionlist = async () => {
    // console.log(queryForm.value.query)
    const res = await getaddquestionlist({
      param: queryForm.value.query
    })
    // console.log(res.subjectlist)
    const arr = []
    for (let i = 0; i < res.subjectlist.length; i++) {
      arr.push({ label: res.subjectlist[i].subject, value: res.subjectlist[i].subject })
    }
    arr.push({ label: '请选择科目', value: '' })
    queryForm.value.subject = arr
    queryForm.value.typeValue = ''
    queryForm.value.subjectValue = ''
    questionlist.value = res.questionlist
    resultlist.value = res.questionlist
    queryForm.value.totle = res.questionlist.length
    handleCurrentChange(1)
  }
  // 分页展示表格
  const initTableData = () => {
    const start = (queryForm.value.pagename - 1) * queryForm.value.pagesize
    let end = queryForm.value.pagename * queryForm.value.pagesize
    end = end < queryForm.value.totle ? end : queryForm.value.totle
    const arr = []
    for (let i = start; i < end; i++) {
      arr.push(resultlist.value[i])
    }
    tableData.value = arr
  }
  initGetQuestionlist()
  // 改变分页
  const handleCurrentChange = (number) => {
    queryForm.value.pagename = number
    initTableData()
  }

  // 转换题目类型
  const changeType = (str) => {
    switch (str) {
      case 'tian': return '填空题'
      case 'duo': return '多选题'
      case 'pan': return '判断题'
      case 'dan': return '单选题'
    }
  }

  // 筛选
  const screen = () => {
    const arr = []
    for (let i = 0; i < questionlist.value.length; i++) {
      if (questionlist.value[i].subject.indexOf(queryForm.value.subjectValue) !== -1 && questionlist.value[i].type.indexOf(queryForm.value.typeValue) !== -1) {
        arr.push(questionlist.value[i])
      }
    }
    queryForm.value.totle = arr.length
    resultlist.value = arr
    handleCurrentChange(1)
  }

  // 编辑/新增问题表单弹窗
  const dialogVisible = ref(false)
  const question = ref({
    id: 0,
    title: '',
    subject: '',
    newsubject: '',
    type: 'dan',
    options: [],
    answer: '',
    analysis: '',
    isaddsubject: false
  })
  // 获取全部科目
  const subjectlist = ref([])
  const initselectsubjectlist = async () => {
    const res = await getsubjectlist()
    const arr = []
    for (let i = 0; i < res.subjectlist.length; i++) {
      arr.push({ label: res.subjectlist[i].subject, value: res.subjectlist[i].subject })
    }
    subjectlist.value = arr
  }
  initselectsubjectlist()
  // 修改答案
  const setanswer = (index) => {
    const char = String.fromCharCode(65 + index)
    if (question.value.type === 'duo') {
      if (question.value.answer.indexOf(char) === -1) {
        const chars = question.value.answer.split('')
        let index = 0
        for (let i = 0; i < chars.length; i++) {
          // console.log(i, char, chars[i])
          if (i === 0 && char < chars[i]) {
            index = 0
            break
          } else if (i === chars.length - 1 && char > chars[i]) {
            index = i + 1
            break
          } else if (char < chars[i]) {
            index = i
            break
          }
        }
        // console.log(index)
        chars.splice(index, 0, char)
        question.value.answer = chars.join('')
      } else {
        question.value.answer = question.value.answer.replace(char, '')
      }
    } else {
      question.value.answer = char
    }
  }
  // 添加选项
  const addoption = () => {
    question.value.options.push({ option: '' })
  }
  // 删除选项
  const deloption = (index) => {
    question.value.options.splice(index, 1)
    // 修改答案
    question.value.answer = question.value.answer.replace(String.fromCharCode(65 + index), '')
    const chars = question.value.answer.split('')
    console.log(question.value.answer)
    for (let i = 0; i < chars.length; i++) {
      if (chars[i] > String.fromCharCode(65 + index)) {
        chars[i] = String.fromCharCode(chars[i].charCodeAt() - 1)
      }
    }
    question.value.answer = chars.join('')
  }
  // 改变题目类型
  const changeSelectType = (value) => {
    question.value.answer = ''
  }
  // const isfix = ref(false)
  // 自定义表单校验规则
  const validateOption = (rule, value, callback) => {
    const arr = question.value.options
    if (arr.length === 0) {
      return callback(new Error('不能没有选项'))
    } else {
      let flag = false
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].option === '') {
          flag = true
          break
        }
      }
      if (flag) {
        return callback(new Error('选项内容不能为空'))
      } else {
        return callback()
      }
    }
  }
  const rules = ref({
    title: [
      { required: true, message: '输入内容不能为空', trigger: 'blur' }
    ],
    subject: [
      { required: true, message: '必须选择科目', trigger: 'blur' }
    ],
    newsubject: [
      { required: true, message: '输入内容不能为空', trigger: 'blur' }
    ],
    option: [{ validator: validateOption, trigger: 'blur' }],
    analysis: [
      { required: true, message: '输入内容不能为空', trigger: 'blur' }
    ],
    answer: [
      { required: true, message: '输入内容不能为空', trigger: 'blur' }
    ]
  })
  const opendialog = (item) => {
    dialogVisible.value = true
    question.value = JSON.parse(JSON.stringify(item))
  }
  // 关闭/取消弹窗
  const closedialo = () => {
    question.value = {
      id: 0,
      title: '',
      subject: '',
      newsubject: '',
      type: 'dan',
      options: [],
      answer: '',
      analysis: '',
      isaddsubject: false
    }
    // isfix.value = false
    dialogVisible.value = false
  }
  // 提交
  const formRef = ref(null)
  const summit = (isadd) => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        setaddquestion({
          ...question.value,
          isadd
        }).then(res => {
          // console.log(res)
          closedialo()
          ElMessage.success(res.msg)
          initGetQuestionlist()
        })
      } else {
        return false
      }
    })
  }
  // 直接添加题目
  const addquestion = (item) => {
    ElMessageBox.confirm(
      '是否直接添加该题目入题库',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    .then(() => {
      setaddquestion({
        ...JSON.parse(JSON.stringify(item)),
        isadd: true
      }).then(res => {
        // console.log(res)
        closedialo()
        ElMessage.success(res.msg)
        initGetQuestionlist()
      })
    })
  }
  // 删除题目
  const deleteQuestion = (id) => {
    ElMessageBox.confirm(
      '是否删除该题目',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    .then(() => {
      deladdquestion({
        id
      }).then(res => {
        ElMessage.success(res.msg)
        initGetQuestionlist()
      })
    })
}
</script>

<style lang="scss" scoped>
  .header {
    padding-bottom: 16px;
    box-sizing: border-box;
  }
  ::v-deep .el-image {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }
  ::v-deep .el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 16px;
  }
  .m-2 {
    margin: 0 10px;
  }
  .answer {
    color: red;
    font-weight: bolder;
  }
</style>
